import { useEffect, useState } from "react";
import "./promotion.css";
import {
  Card,
  Row,
  Col,
  Button,

  Input,
  Select,
  Table,
  Tag,
  Space,
  Skeleton,
  Tooltip,
  Typography,
  message,

  Form,

} from "antd";
import {
  SearchOutlined,

  ClockCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,

} from "@ant-design/icons";

import { CustomerDetailModal } from "../../component/promotion/CustomerDetailModal";

const { Title, Text } = Typography;


// 原有：客户模拟数据（新增keyword字段，关联关键字）
const customerData = [
  {
    id: "PRO2023001",
    name: "张三",
    phone: "138****8000",
    type: "vip",
    source: "微信推广",
    plan: "中医推拿体验啊啊啊啊啊啊",
    keyword: "中医推拿", // 新增：客户来源关键字
    date: "2023-06-15",
    status: "已完成",
    follower: "李员工",
    nextFollow: "--",
  },
  {
    id: "PRO2023002",
    name: "李四",
    phone: "139****9000",
    type: "clue",
    source: "客户推荐",
    plan: "针灸理疗套餐",
    keyword: "针灸理疗", // 新增：客户来源关键字
    date: "2023-06-12",
    status: "跟进中",
    follower: "王员工",
    nextFollow: "2023-06-20",
  },
  {
    id: "PRO2023003",
    name: "王五",
    phone: "137****7000",
    type: "clue",
    source: "宣传单页",
    plan: "艾灸养生体验",
    keyword: "艾灸养生", // 新增：客户来源关键字
    date: "2023-06-10",
    status: "待跟进",
    follower: "张员工",
    nextFollow: "2023-06-18",
  },
  {
    id: "PRO2023004",
    name: "赵六",
    phone: "135****5000",
    type: "public",
    source: "支付宝推广",
    plan: "全身SPA套餐",
    keyword: "SPA放松", // 新增：客户来源关键字
    date: "2023-06-08",
    status: "已放弃",
    follower: "刘员工",
    nextFollow: "--",
  },
  {
    id: "PRO2023005",
    name: "孙七",
    phone: "136****6000",
    type: "vip",
    source: "微信推广",
    plan: "拔罐理疗体验",
    keyword: "拔罐理疗", // 新增：客户来源关键字
    date: "2023-06-05",
    status: "已完成",
    follower: "李员工",
    nextFollow: "--",
  },
  {
    id: "PRO2023006",
    name: "周八",
    phone: "134****4000",
    type: "clue",
    source: "其他渠道",
    plan: "推拿按摩套餐",
    keyword: "推拿按摩", // 新增：客户来源关键字
    date: "2023-06-03",
    status: "跟进中",
    follower: "王员工",
    nextFollow: "2023-06-19",
  },
  {
    id: "PRO2023007",
    name: "吴九",
    phone: "133****3000",
    type: "public",
    source: "客户推荐",
    plan: "中药熏蒸体验",
    keyword: "中药熏蒸", // 新增：客户来源关键字
    date: "2023-06-01",
    status: "已放弃",
    follower: "张员工",
    nextFollow: "--",
  },
  {
    id: "PRO2023008",
    name: "郑十",
    phone: "132****2000",
    type: "clue",
    source: "宣传单页",
    plan: "刮痧理疗体验",
    keyword: "刮痧理疗", // 新增：客户来源关键字
    date: "2023-05-28",
    status: "待跟进",
    follower: "刘员工",
    nextFollow: "2023-06-17",
  },
];

// 原有：工具函数
const renderEllipsisText = (text, maxLength = 11) => {
  if (!text || text.length <= maxLength) return text;
  return (
    <Tooltip title={text} placement="top">
      <span className="ellipsis-text">{text.slice(0, maxLength)}...</span>
    </Tooltip>
  );
};

const renderCustomerType = (type) => {
  switch (type) {
    case "clue":
      return <Tag color="blue" size="small">线索客户</Tag>;
    case "vip":
      return <Tag color="gold" size="small">VIP客户</Tag>;
    case "public":
      return <Tag color="green" size="small">公海客户</Tag>;
    default:
      return <Tag size="small">{type}</Tag>;
  }
};

const renderStatusTag = (status) => {
  switch (status) {
    case "已完成":
      return <Tag color="green" size="small"><CheckCircleOutlined /> 已完成</Tag>;
    case "跟进中":
      return <Tag color="processing" size="small"><ClockCircleOutlined /> 跟进中</Tag>;
    case "待跟进":
      return <Tag color="orange" size="small"><ClockCircleOutlined /> 待跟进</Tag>;
    case "已放弃":
      return <Tag color="red" size="small"><CloseCircleOutlined /> 已放弃</Tag>;
    default:
      return <Tag size="small">{status}</Tag>;
  }
};


export const Promotion = () => {
  const [isShowSkeleton, setIsShowSkeleton] = useState(true);
  const [searchParams, setSearchParams] = useState({
    keyword: "",
    source: "",
    type: "",
    status: "",
    promotionKeyword: "", // 新增：关键字筛选
  });
  const [customers, setCustomers] = useState(customerData);
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentCustomer, setCurrentCustomer] = useState(null);

  // 原有：骨架屏控制
  useEffect(() => {
    const timer = setTimeout(() => {
      setIsShowSkeleton(false);
    }, 2000);
    return () => clearTimeout(timer);
  }, []);




  // 原有：客户表格列（新增“推广关键字”筛选列）
  const customerColumns = [
    {
      title: "客户ID",
      dataIndex: "id",
      key: "id",
      width: 100, // 固定宽度
      render: (text) => text,
    },
    {
      title: '客户姓名',
      dataIndex: 'name',
      key: 'name',
      width: 120, // 固定宽度
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      key: 'phone',
      width: 120, // 固定宽度
      render: (text) => text,
    },
    // {
    //   title: '客户类型',
    //   dataIndex: 'type',
    //   key: 'type',
    //   width: 100, // 新增固定宽度
    //   render: (type) => renderCustomerType(type),
    // },
    {
      title: '推广来源',
      dataIndex: 'source',
      key: 'source',
      width: 130, // 新增固定宽度

      ellipsis: true, // 现在可生效
      render: (text) => renderEllipsisText(text), // 可选：保留自定义 ellipsis 逻辑
    },
    {
      title: '推广方案',
      dataIndex: 'plan',
      key: 'plan',
      width: 150, // 固定宽度（确保足够显示截断文本）
      render: (text) => renderEllipsisText(text, 7)
    },
    {
      title: '推广日期',
      dataIndex: 'date',
      key: 'date',
      width: 120, // 新增固定宽度

    },
    {
      title: '跟进状态',
      dataIndex: 'status',
      key: 'status',
      width: 130, // 新增固定宽度

      render: (status) => renderStatusTag(status),
    },
    {
      title: '跟进人',
      dataIndex: 'follower',
      key: 'follower',
      width: 100, // 新增固定宽度

      ellipsis: true, // 可选：添加 ellipsis
    },
    {
      title: '下次跟进时间',
      dataIndex: 'nextFollow',
      key: 'nextFollow',
      width: 130, // 新增固定宽度
      ellipsis: true, // 可选：添加 ellipsis
    },
    {
      title: '操作',
      fixed: 'right',
      width: 120, // 固定宽度（右侧固定列必须有宽度）
      key: 'action',
      render: (_, record) => (<Space size="small">
        <Button
          type="primary"
          size="small"
          style={{ padding: '4px 8px' }} // 移动端缩小按钮内边距
          onClick={() => {
            setCurrentCustomer(record);
            setDetailVisible(true);
          }}
        >
          详情
        </Button>
      </Space>),
    },
  ];

  // 原有：处理搜索参数变化（新增关键字筛选参数）
  const handleSearchChange = (key, value) => {
    setSearchParams({
      ...searchParams,
      [key]: value
    });
  };

  // 原有：执行搜索（新增关键字筛选逻辑）
  const handleSearch = () => {
    let filteredCustomers = [...customerData];

    // 其他原有筛选逻辑
    if (searchParams.keyword) {
      filteredCustomers = filteredCustomers.filter(customer =>
        customer.name.includes(searchParams.keyword) ||
        customer.phone.includes(searchParams.keyword)
      );
    }
    if (searchParams.source && searchParams.source !== "all") {
      filteredCustomers = filteredCustomers.filter(customer =>
        customer.source === searchParams.source
      );
    }

    setCustomers(filteredCustomers);
    message.success(`找到 ${filteredCustomers.length} 条匹配记录`);
  };


  // 原有：处理跟进记录
  const handleFollowUp = (record, nextDate, status) => {
    setCustomers(prevCustomers =>
      prevCustomers.map(customer => {
        if (customer.id === currentCustomer.id) {
          return {
            ...customer,
            status,
            nextFollow: nextDate || '--'
          };
        }
        return customer;
      })
    );
    setCurrentCustomer(prev => ({
      ...prev,
      status,
      nextFollow: nextDate || '--'
    }));
  };

  // 原有：推广来源（补充“全部来源”选项）
  const sourceData = [
    { value: "all", label: "全部来源" },
    { value: "微信推广", label: "微信推广" },
    { value: "支付宝推广", label: "支付宝推广" },
    { value: "客户推荐", label: "客户推荐" },
    { value: "宣传单页", label: "宣传单页" },
    { value: "其他渠道", label: "其他渠道" }
  ];




  return (
    <div className="promotion-container">
      {isShowSkeleton ? (
        <Skeleton
          paragraph={{ rows: 6 }}
          active
          style={{ width: '100%' }}
        />
      ) : (
        <>
          {/* 1. 页面标题+操作区 */}
          <div style={{
            display: 'flex',
            flexDirection: 'column',
            gap: 16,
            marginBottom: 20,
            width: '100%'
          }}>
            <div>
              <Title level={2} style={{
                margin: 0,
                fontSize: 'clamp(1.5rem, 3vw, 1.875rem)',
                width: '100%'
              }}>推广管理</Title>
              <Text type="secondary">显示所有被推广的客户及关联关键字</Text>
            </div>

            {/* 2. 搜索和筛选区 */}
            <Card style={{

              width: "91%",
              boxSizing: 'border-box'
            }}>
              <Row gutter={[12, 12]}>
                {/* 客户名称/电话搜索 */}
                <Col xs={24} sm={12} md={6} lg={5}>
                  <label className="search-title" style={{
                    fontSize: '14px',
                    display: 'block',
                    marginBottom: 6
                  }}>
                    客户名称/电话
                  </label>
                  <Input
                    placeholder="请输入客户名称或电话"
                    value={searchParams.keyword}
                    onChange={(e) => handleSearchChange('keyword', e.target.value)}
                    size="small"
                    style={{ width: '100%' }}
                  />
                </Col>

                {/* 推广来源筛选 */}
                <Col xs={24} sm={12} md={6} lg={5}>
                  <label className="search-title" style={{
                    fontSize: '14px',
                    display: 'block',
                    marginBottom: 6
                  }}>
                    推广来源
                  </label>
                  <Select
                    defaultValue="all"
                    style={{ width: '100%' }}
                    onChange={(value) => handleSearchChange('source', value)}
                    options={sourceData}
                    size="small"
                  />
                </Col>


                {/* 搜索按钮区域 */}
                <Col xs={24} sm={12} md={6} lg={4} style={{
                  marginTop: 30,
                  position: "absolute",
                  right: 10
                }}>
                  <Space size="small">

                    <Button
                      type="primary"
                      icon={<SearchOutlined />}
                      onClick={handleSearch}
                      size="small"
                    >
                      搜索
                    </Button>
                  </Space>
                </Col>
              </Row>
            </Card>

            {/* 3. 客户表格 */}
            <Card style={{ width: "91%", boxSizing: 'border-box' }}>
              <Table
                columns={customerColumns}
                dataSource={customers}
                rowKey="id"
                bordered
                pagination={{
                  pageSize: 6,
                  total: customers.length,
                  showSizeChanger: false,
                  showTotal: (total) => `共 ${total} 条记录`,
                  size: "small"
                }}
                scroll={{ x: 'max-content', minWidth: 900 }}
                rowClassName="mobile-table-row"
                style={{
                  fontSize: '14px',
                  width: '100%',
                  tableLayout: 'fixed'
                }}
              />
            </Card>



          </div>

          {/* 4. 客户详情模态框 */}
          <CustomerDetailModal
            visible={detailVisible}
            onClose={() => setDetailVisible(false)}
            customer={currentCustomer}
            onFollowUp={handleFollowUp}
          />


        </>
      )}
    </div>

  );
};